package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Category;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Controller
@RequestMapping("/admin_catalog")
public class Admin_CatalogController {
    @Autowired
    private CatalogService catalogService;

    private List<String> CATEGORY_LIST;
    private List<String> PRODUCT_LIST;

    @GetMapping("/admin_view")
    public String admin_view(Model model){
        //后台添加Category后，获取新的categoryList,但categoeyList的显示列表的页面还未完成，无法查看结果
        List<Category> categoryList = catalogService.getCategoryList();
        //测试是否添加成功
        System.out.println(categoryList.size());
        model.addAttribute("categoryList",categoryList);
        return "admin/main";

    }

    @GetMapping("/admin_goods")
    public String admin_viewGoods(){
        return "admin/goods";

    }

    @GetMapping("/admin_addGood")
    public String admin_addGood(){
        return "admin/addGood";

    }

    @GetMapping("/admin_addCategory")
    public String adminAddCategory(Model model){
        //参考newAccountForm，新建一个category,放到model中
        model.addAttribute("newCategory", new Category());
        return "admin/addCategory";
    }
    //管理员新增一个category
    @PostMapping("/addCategory")
    public String addCategory(@ModelAttribute(value = "newCategory")Category category,Model model){

        System.out.println("categoryId:"+category.getCategoryId()+" "+category.getName());
        catalogService.insertCategory(category);
        List<Category> categoryList = catalogService.getCategoryList();
        //测试是否添加成功
        System.out.println(categoryList.size());
        model.addAttribute("categoryList",categoryList);
        return "redirect:/admin_catalog/admin_view";

    }

    @GetMapping("/admin_addProduct")
    public String admin_addProduct(Model model){
        model.addAttribute("newProduct",new Product());
        List<Category> categoryList = catalogService.getCategoryList();
        //测试是否添加成功
        System.out.println(categoryList.size());
        List<String> catList = new ArrayList<String>();
        for(int i=0;i<categoryList.size();i++){
            catList.add(categoryList.get(i).getCategoryId());
        }
        CATEGORY_LIST = Collections.unmodifiableList(catList);
        model.addAttribute("CATEGORY_LIST",CATEGORY_LIST);

        return "admin/addProduct";

    }
    @PostMapping("/addProduct")
    public String addProduct(@ModelAttribute(value = "newProduct")Product product, MultipartFile file , HttpServletRequest request){
        //前台负责检查是否重复了productId
        System.out.println("productId:"+product.getProductId()+" "+product.getName());
        System.out.println("categoryId:"+product.getCategoryId());
        //处理：图片的地址和描述信息合并到description
        //定义文件保存路径
        String fileOriginName = file.getOriginalFilename();
        String fileType = fileOriginName.substring(fileOriginName.lastIndexOf("."),fileOriginName.length());
        //System.out.println(fileType);
        String filename = product.getProductId()+fileType;
        String path = "images/"+product.getProductId()+fileType;
        //写入
        try{
            File file_ = new File(new File("").getAbsolutePath().replace("\\","/")+"/src/main/resources/static/images",filename);
            //debug
            System.out.println(file_.getAbsolutePath());
            file_.createNewFile();
            FileOutputStream out = new FileOutputStream(file_);
            out.write(file.getBytes());
            out.close();
        }catch(IOException e){
            e.printStackTrace();
        }
        String descriptionImage = "<image src=\""+path+"\">";
        product.setDescriptionImage(descriptionImage);
        product.setDescription(product.getDescriptionImage()+product.getDescriptionText());
        System.out.println("description:"+product.getDescription());

        catalogService.insertProduct(product);
        return "redirect:/admin_catalog/admin_viewCategory?categoryId="+product.getCategoryId();

    }

    @GetMapping("/admin_addItem")
    public String admin_addItem(Model model){
        model.addAttribute("newItem",new Item());
        List<Category> categoryList = catalogService.getCategoryList();
        //测试是否添加成功
        System.out.println(categoryList.size());
        //添加item时需要先选择它所属的category和product
        List<String> catList = new ArrayList<String>();
        for(int i=0;i<categoryList.size();i++){
            catList.add(categoryList.get(i).getCategoryId());
        }
        CATEGORY_LIST = Collections.unmodifiableList(catList);
        model.addAttribute("CATEGORY_LIST",CATEGORY_LIST);

        List<Product> productList = catalogService.getProductList();
        List<String> proList = new ArrayList<String>();
        for(int i=0;i<productList.size();i++){
            proList.add(productList.get(i).getProductId());
        }
        PRODUCT_LIST = Collections.unmodifiableList(proList);
        model.addAttribute("PRODUCT_LIST",PRODUCT_LIST);

        return "admin/addItem";

    }
    @PostMapping("/addItem")
    public String addItem(@ModelAttribute(value = "newItem")Item item){
        //前台负责检查是否重复了categoryId
        System.out.println("itemId:" + item.getItemId() + "productId" + item.getProductId() + "quantity" + item.getQuantity() + "price" + item.getListPrice());
        //设置供应商和销售状态
        item.setStatus("P");
        item.setSupplierId(1);
        //插入到item中，这里的插入是一个事务，也在inventory库存表中也进行了插入
        catalogService.insertItem(item);
        return "redirect:/admin_catalog/admin_viewProduct?productId=" + item.getProductId();

    }
    //script判断所添加的CategoryId是否已存在
    @ResponseBody
    @RequestMapping(value = "/CheckCategoryId",method= RequestMethod.GET)
    public String CheckCategoryId(String categoryId){
        System.out.println("************************");
        if(catalogService.isCategoryIdExist(categoryId)){
            return "Exist";
        }
        else return "Not Exist";
    }
    //script判断所添加的ProductId是否已存在
    @ResponseBody
    @RequestMapping(value = "/CheckProductId",method= RequestMethod.GET)
    public String CheckProductId(String productId){
        System.out.println("********//////////");
        if(catalogService.isProductIdExist(productId)){
            return "Exist";
        }
        else return "Not Exist";
    }
    //script判断所添加的ItemId是否已存在
    @ResponseBody
    @RequestMapping(value = "/CheckItemId",method= RequestMethod.GET)
    public String CheckItemId(String itemId){
        System.out.println("********//////////");
        if(catalogService.isItemIdExist(itemId)){
            return "Exist";
        }
        else return "Not Exist";
    }
    @GetMapping("/admin_viewCategory")
    public String admin_viewCategory(String categoryId, Model model){

        if(categoryId != null){
            Category category = catalogService.getCategory(categoryId);
            List<Product>  productList = catalogService.getProductListByCategory(categoryId);
            model.addAttribute("category",category);
            model.addAttribute("productList",productList);
            return "admin/a_category";
        }

        return "admin/main";

    }

    @GetMapping("/admin_viewProduct")
    public String admin_viewProduct(String productId, Model model){

        if(productId != null){
            Product product = catalogService.getProduct(productId);
            List<Item> itemList = catalogService.getItemListByProduct(productId);
            model.addAttribute("product",product);
            model.addAttribute("itemList",itemList);
            return "admin/a_product";
        }

        return "admin/main";

    }

    @GetMapping("/admin_viewItem")
    public String admin_viewItem(String itemId, Model model){

        if(itemId != null){
            Item item = catalogService.getItem(itemId);
            Product product = catalogService.getProduct(item.getProductId());
            processProductDescription(product);
            model.addAttribute("item",item);
            model.addAttribute("product",product);

            return "admin/a_item";
        }

        return "admin/main";

    }

    @GetMapping("/admin_changeProduct")
    public String admin_changeProduct(String productId, Model model){

        if(productId != null){
            Product product = catalogService.getProduct(productId);
            List<Item> itemList = catalogService.getItemListByProduct(productId);
            model.addAttribute("product",product);
            model.addAttribute("itemList",itemList);
            return "admin/edit_product";
        }

        return "admin/a_product";

    }

    @GetMapping("/admin_changeItem")
    public String admin_changeItem(String itemId, Model model){

        if(itemId != null){
            Item item = catalogService.getItem(itemId);
            Product product = catalogService.getProduct(item.getProductId());
            processProductDescription(product);
            model.addAttribute("item",item);
            model.addAttribute("product",product);

            return "admin/edit_item";
        }

        return "admin/a_item";

    }

    @GetMapping("/admin_updateProduct")
    public String admin_updateProduct(String oldProductId,String newDescription,String newName, Model model){


            Product product = catalogService.getProduct(oldProductId);
            product.setName(newName);
            product.setDescription(newDescription);
//             product.setDescriptionImage(newDescriptionImage);
//             product.setDescriptionText(newDescriptionText);
            catalogService.updateProduct(oldProductId,product);
            model.addAttribute("product",product);
            System.out.println(product.getProductId());
            System.out.println(product.getName());
            System.out.println(product.getDescription());
            return "admin/goods";

    }

    @GetMapping("/admin_updateItem")
    public String admin_updateItem(String itemId,String ProductId,String newListPrice,
                                   String newUnitCost, String newQuantity,String newSupplierId,
                                   String newAttribute1, Model model) {


        Product product = catalogService.getProduct(ProductId);
        Item item = catalogService.getItem(itemId);
        //转换数据类型
        BigDecimal bd = new BigDecimal(newListPrice);
        BigDecimal bd2 = new BigDecimal(newUnitCost);
        int quantity = Integer.parseInt(newQuantity);
        int supplierId = Integer.parseInt(newSupplierId);
        item.setListPrice(bd);
        item.setUnitCost(bd2);
        item.setQuantity(quantity);
        item.setSupplierId(supplierId);
        item.setAttribute1(newAttribute1);
        catalogService.updateItem(itemId, item);
        catalogService.update2InventoryQuantity(itemId, quantity);
        model.addAttribute("item", item);
        model.addAttribute("product", product);
        System.out.println(item.getQuantity());


        return "admin/a_category";
    }
    //在浏览某一category时增加product
    @GetMapping("addProductForm")
    public String addProductForm(Model model,String categoryId){
        //Category category = catalogService.getCategory(categoryId);
        //model.addAttribute("category",category);
        Product product = new Product();
        product.setCategoryId(categoryId);
        model.addAttribute("product",product);
        //model.addAttribute("categoryId",categoryId);
        return "admin/addProduct";
    }
    @GetMapping("/admin_deleteProduct")
    public String admindeleteProduct(String productId,Model model){
        Product product = catalogService.getProduct(productId);
        String categoryId = product.getCategoryId();
        catalogService.deleteItemByProductId(productId);
        catalogService.deleteProduct(productId);
        Category category = catalogService.getCategory(categoryId);
        model.addAttribute("category",category);
        return admin_viewCategory(categoryId,model);

    }

    @GetMapping("/admin_deleteItem")
    public String admindeleteItem(String itemId,Model model){
        Item item = catalogService.getItem(itemId);
        String productId = item.getProductId();
        catalogService.deleteItemByItemId(itemId);
        Product product = catalogService.getProduct(productId);
        model.addAttribute("product",product);
        return admin_viewProduct(productId,model);

    }
    //目前未使用
    @PostMapping("uploadPicture")
    public String uploadPicture(MultipartFile file){
        //获取文件名
        String filename = file.getOriginalFilename();
        //debug
        System.out.println("filename:"+filename);
        //定义文件保存路径，到时候返回给前端
        String path = "images/"+filename;
        //写入
        try{
            file.transferTo(new File(path));
        }catch(IOException e){
            e.printStackTrace();
        }
        //写入数据库（交表时做）

        //将path返回给前端
        String descriptionImage = "<image src=\""+path+"\">";
        return descriptionImage;

    }


    //解决thymeleaf不识别<image>
    private void processProductDescription(Product product){
        String [] temp = product.getDescription().split("\"");
        product.setDescriptionImage(temp[1]);
        product.setDescriptionText(temp[2].substring(1));
    }

    private void processProductDescription(List<Product> productList){
        for(Product product : productList) {
            processProductDescription(product);
        }
    }

}

